var listOrder = new Array;	

/*	
function createQuestionsOrder(selectedCatagory) {
	var listLength = questionArray.length;
	for (i = 0; i < listLength; i ++) { 
		listOrder[i] = i;
		};
	shuffle(listOrder);
}	
*/

function createQuestionsOrder(selectedCatagory) {
	var listLength = questionArray.length;
	var questionsInThisCatagory = [];
	for (i = 0; i < listLength; i ++) { 
		for (o = 0; o < questionArray[i].catagories.length; o++) {
			if (questionArray[i].catagories[o] == selectedCatagory) {
				questionsInThisCatagory.push(i);
			}
		}
		listOrder[i] = i;
		};
	//alert(questionsInThisCatagory.length);
	//shuffle(listOrder);
	shuffle(questionsInThisCatagory);
}	
	
//shuffles list in-place
function shuffle(list) {
  var i, j, t;
  for (i = 1; i < list.length; i++) {
    j = Math.floor(Math.random()*(1+i));  // choose j in [0..i]
    if (j != i) {
      t = list[i];                        // swap list[i] and list[j]
      list[i] = list[j];
      list[j] = t;
    }
  }
  //listOrder = list;
  questionsInThisCatagory = list;
}	

// jQuery Shuffler from CSSTricks http://css-tricks.com/snippets/jquery/shuffle-dom-elements/
(function($){
 
    $.fn.shuffle = function() {
 
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
 
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
 
        return $(shuffled);
 
    };
 
})(jQuery);

function compileQuestion(questionNumber){
	var thisQuestion = "";
	thisQuestion = thisQuestion + "<h2>" + questionArray[questionNumber].question + "</h2><div id='result'></div>";
	thisQuestion = thisQuestion + "<a href='#' data-role='button' data-icon='star' class='answer-button qnum1' >" + questionArray[questionNumber].answer1 + "</a>";
	thisQuestion = thisQuestion + "<a href='#' data-role='button' data-icon='star' class='answer-button qnum2' >" + questionArray[questionNumber].answer2 + "</a>";
	thisQuestion = thisQuestion + "<a href='#' data-role='button' data-icon='star' class='answer-button qnum3' >" + questionArray[questionNumber].answer3 + "</a>";
	return thisQuestion;
}

function generateQuestion(questionNumber) {
	var thisQuestion = compileQuestion(questionNumber);
	$("content").fadeIn();
	$("#current-question").append(thisQuestion);
	$('a').shuffle();
	$("content").trigger('create');
	$(".answer-button").click(function() { 
		if ( $(this).hasClass('qnum1') ) {selectedAnswerNumber = 1; selectedClass = 'qnum1';};
		if ( $(this).hasClass('qnum2') ) {selectedAnswerNumber = 2; selectedClass = 'qnum2';};
		if ( $(this).hasClass('qnum3') ) {selectedAnswerNumber = 3; selectedClass = 'qnum3';};
		checkAnswer(questionNumber, selectedAnswerNumber, selectedClass); 
	});
}
	
function checkAnswer(thisQuestionNumber, selectedAnswerNumber, selectedClass) {
	$("span.ui-btn-inner").css({'background-color': '#ffaaaa'});
	if (selectedAnswerNumber == questionArray[thisQuestionNumber].correctAnswer) {
		$("a." + selectedClass).buttonMarkup({ icon: "check" });
		$("a." + selectedClass + " span.ui-btn-inner").css({'background-color': '#aaffaa'});
		$("#result").append("<p>Correct Answer!</p>").css({"color": "#009900"});
		score ++;
		$("#score-total").empty().append(score);
	} else { 
		$("a." + selectedClass).buttonMarkup({ icon: "delete" });
		$("a.qnum" + questionArray[thisQuestionNumber].correctAnswer + " span.ui-btn-inner").css({'background-color': '#aaffaa'});
		$("#result").append("<p>Wrong Answer!</p>").css({"color": "#cc0000"});
	};
	$("#next-button-container").append("<a href='#' data-role='button' data-icon='arrow-r' data-mini='true' class='next-button' style='margin-top:20px;' >NEXT</a>");
	$("#next-button-container").fadeIn('slow', function() {});
	$("content").trigger('create');
	$(".next-button").click(function() {
		clearQuestion();
		questionTotal ++;
		$("#question-number").empty().append(questionTotal + 1);
	});
};

function clearQuestion() {
	$("content").fadeOut('fast', function() {
		$("#current-question").empty()
		$(".next-button").remove();
		$("#next-button-container").fadeOut();
		currentQuestionNumber = questionsInThisCatagory[questionTotal];
		if (questionTotal == questionsInThisCatagory.length) { 
				endGame(); 
			} else {
				generateQuestion(currentQuestionNumber, selectedCatagory); 
			};
	});
}

function showQuestionNumber() {
	$("#question-number").append(questionTotal + 1);
	$("#score-total").append(score);
}

function generateCatagoryList() {
	var catsMessage = "Pick a catagory:";
	catsMessage = "<ul data-role='listview' data-inset='true'><li><a href='#'>General</a></li><li><a href='#'>Stories</a></li><li><a href='#'>Characters</a></li><li><a href='#'>Locations</a></li><li><a href='#'>Quotes</a></li><li><a href='#'>M.R. James's Life</a></li></ul>";
	$("content").fadeIn();
	$("#current-question").append(catsMessage);
	$("content").trigger('create');
	$("content a").each(function(index) {
		$("content a").eq(index).click(function() {
			selectedCatagory = index;
			$("content").fadeOut('fast', function() {
				clearQuestion();
				createQuestionsOrder(selectedCatagory);
				generateQuestion(listOrder[questionTotal]);
			});
		});
	});
}

function showStartScreen() {
	var startMessage = "";
	startMessage = startMessage + "<div style='text-align:center'><img src='images/Website-logo2.gif' alt='A Podcast to the Curious Logo' /></div>";
	startMessage = startMessage + "<h1>M.R. James Trivia Quiz</h1><h2 class='titlepage'>Test your ghost story knowledge!</h2>";
	startMessage = startMessage + "<p><a href='#' data-role='button' data-icon='arrow-r' data-iconpos='right' class='start-button' style='margin-top:20px;' >START</a></p>";
	startMessage = startMessage + "<p><a href='#' data-role='button' data-icon='arrow-r' data-iconpos='right' class='cats-button' style='margin-top:20px;' >CATAGORIES</a></p>";
	$("#current-question").append(startMessage);
	$("content").trigger('create');
	$(".start-button").click(function() {
		$("content").fadeOut('fast', function() {
			createQuestionsOrder(selectedCatagory);
			clearQuestion();
			generateQuestion(questionsInThisCatagory[questionTotal]);
		});
	});
	$(".cats-button").click(function() {
		$("content").fadeOut('fast', function() {
			$("#current-question").empty()
			$(".next-button").remove();
			$("#next-button-container").fadeOut();
			generateCatagoryList();
		});
	});
}

function socialMediaScore(userScore, outOf) {
	var socialMedia = '<div id="tweet-this"><a href="https://twitter.com/intent/tweet?button_hashtag=MRJamesQuiz&text=I%20scored%20' + userScore + '%20out%20of%20' + outOf +'%20on%20the%20M.R.%20James%20Quiz!" class="twitter-hashtag-button" data-size="large" data-url="http://mrjp.me/quiz" data-dnt="true">Tweet Your Score!</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';
	// socialMedia = socialMedia + '<iframe src="https://www.facebook.com/plugins/like.php?href=http://mrjp.me" scrolling="no" frameborder="0" style="border:none; width:100%; height:80px; text-align:center; margin-top:30px;"></iframe></div>';
	return socialMedia;
}

function endGame() {
	$("content").fadeIn();
	$("#question-number-heading").empty();
	$("#score").empty();
	var catagoryWords = ['general','Which story','Characters','Locations','Quotes','Monty\'s Life'];
	var endMessage = "<h2>Well done!</h2><h2>You  got " + score + " out of " + questionTotal + " questions correct.</h2>";
	endMessage = endMessage + "<h3>Catagory: " + catagoryWords[selectedCatagory] + ".</h3>";
	$("#current-question").append(endMessage);
	var socialMedia = socialMediaScore(score, questionTotal);
	$("#current-question").append(socialMedia);
	$("#current-question").after("<a href='#' data-role='button' data-icon='refresh' class='restart-button' style='margin-top:30px;' >RESTART</a>");
	$("content").trigger('create');
	$(".restart-button").click(function() {
		location.reload();
	});
}



var currentQuestionNumber = 0;
var questionTotal = 0;
var score = 0;
var selectedAnswerNumber = 0;
var selectedCatagory = 0;

$(function() {
	$("#next-button-container").fadeOut();
	//alert(questionArray[2].catagories[1]);
	//createQuestionsOrder();
	showStartScreen();
	//generateQuestion(listOrder[questionTotal]);
	showQuestionNumber();
});